package com.example.datahanldernet203204;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class SharedPreferenceActivity  extends AppCompatActivity {


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sharedpreference_act_layout);
        EditText username_et = findViewById(R.id.username_et);
        EditText password_et = findViewById(R.id.password_et);
        Button commit_bt = findViewById(R.id.commit_bt);

        Button show_content_bt = findViewById(R.id.show_content_bt);
        //初始化sharedpreferences对象
        SharedPreferences sp=null;
        //方式一：
         sp = getSharedPreferences("mydata", Context.MODE_PRIVATE);
        //方式二
         //sp = getPreferences(Context.MODE_PRIVATE);
         //方式
         //sp = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences finalSp = sp;
        commit_bt.setOnClickListener((v)->{
            SharedPreferences.Editor edit = finalSp.edit();
            edit.putString("username",username_et.getText().toString());
            edit.putString("password",password_et.getText().toString());
            boolean commit = edit.commit();
            if (commit){
                username_et.setText("");
                password_et.setText("");
            }

        });
        show_content_bt.setOnClickListener((v)->{
            //获取值
            String username = finalSp.getString("username", "");
            username_et.setText(username);
        });

    }
}
